import { createRouter, createWebHistory } from "vue-router";
import Layout from "../layout/Layout.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "Login",
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/",
      component: Layout,
      redirect: "/dashboard",
      children: [
        {
          path: "dashboard",
          name: "Dashboard",
          component: () => import("../views/Dashboard.vue"),
        },
        {
          path: "users",
          name: "Users",
          component: () => import("../views/Users.vue"),
        },
        {
          path: "ai-model",
          name: "AiModel",
          redirect: "/ai-model/models",
          children: [
            {
              path: "models",
              name: "Models",
              component: () => import("../views/ai-model/Models.vue"),
            },
            {
              path: "settings",
              name: "ModelSettings",
              component: () => import("../views/ai-model/ModelSettings.vue"),
            },
            {
              path: "prompts",
              name: "PromptTemplates",
              component: () => import("../views/ai-model/PromptTemplates.vue"),
            },
          ],
        },
        {
          path: "profile",
          name: "Profile",
          component: () => import("../views/Profile.vue"),
        },
        {
          path: "employees",
          name: "Employees",
          component: () => import("../views/Employees.vue"),
          meta: { requiresAdmin: true },
        },
        {
          path: "feedback",
          name: "Feedback",
          component: () => import("../views/Feedback.vue"),
        },
        {
          path: "article",
          name: "Article",
          component: () => import("../views/Article.vue"),
        },
      ],
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
  const userInfo = localStorage.getItem("userInfo");
  const user = userInfo ? JSON.parse(userInfo) : null;

  if (to.path === "/login") {
    if (user) {
      next("/");
    } else {
      next();
    }
  } else {
    if (!user) {
      next("/login");
    } else if (to.meta.requiresAdmin && userInfo.role !== "超级管理员") {
      next("/dashboard");
    } else {
      next();
    }
  }
});

export default router;
